<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>
        <template #right>
          <el-button v-allow="'import_excel'" type="warning" size="small" @click="$router.push('import')">excel导入</el-button>
          <el-button v-allow="'export_excel'" type="danger" size="small" @click="hExportExcel">excel导出</el-button>
          <el-button v-allow="'add_employees'" type="primary" size="small" @click="showDialog=true">新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table border :data="EmployeesList" :default-sort="{prop: 'workNumber', order: 'descending'}">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="工号" sortable prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template #default="{row}">
              {{ formOfEmploymentFormat(row.formOfEmployment) || '未知' }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" sortable prop="timeOfEntry">
            <template v-slot="{row}">
              {{ dataFormat(row.timeOfEntry) }}
            </template>
          </el-table-column>
          <!-- <el-table-column label="账户状态" prop="username" /> -->
          <el-table-column label="操作" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail?id=${row.id}`)">查看</el-button>
              <el-button type="text" size="small" @click="hAssignRole(row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="hDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            :current-page="page"
            :page-sizes="[3, 5, 7, 10]"
            :page-size="size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
      <!-- 新增员工弹层 -->

      <el-dialog title="新增员工" :visible.sync="showDialog">
        <addorEdit v-if="showDialog" @close="showDialog=false" @success="hSuccess" />
      </el-dialog>

      <!-- 分配角色弹层 -->
      <el-dialog
        title="分配角色"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :visible.sync="showDialogRole"
      >
        <assign-role v-if="showDialogRole" :cur-id="curId" @close="showDialogRole=false" @success="hRoleSuccess" />
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getEmployeesList, delEmployee } from '@/api/employees'
// 引入组件
import AssignRole from './assignRole'
import addorEdit from './empDialog'
import dayjs from 'dayjs'
import EmployeesEnum from '@/constant/employees'
// 写在此处这个代码之后执行一次
// const hireType = {}
// EmployeesEnum.hireType.forEach(item => {
//   hireType[item.id] = item.value
// })
const hireType = EmployeesEnum.hireType.reduce((acc, item) => {
  acc[item.id] = item.value
  return acc
}, {})
export default {
  name: 'Employees',
  components: { addorEdit, AssignRole },
  data() {
    return {

      page: 1, // 页面
      size: 3, // 每页条数

      EmployeesList: [], // 员工列表
      total: 0, // 总条数
      showDialog: false, // 控制新增员工弹层
      showDialogRole: false, // 控制分配角色弹层
      curId: '' // 传递id
    }
  },
  created() {
    this.loadEmployeesList()
  },
  methods: {
    // 聘用形式枚举
    formOfEmploymentFormat(id) {
      // const item = EmployeesEnum.hireType.find(item => item.id === id)
      // if (item) {
      //   return item.value
      // } else {
      //   return '未知'
      // }
      return hireType[id]
    },

    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.page = 1
      this.size = val
      this.loadEmployeesList()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.page = val
      this.loadEmployeesList()
    },

    // 获取员工列表
    async loadEmployeesList() {
      try {
        const res = await getEmployeesList({ page: this.page, size: this.size })
        console.log(res)
        this.EmployeesList = res.data.rows
        this.total = res.data.total
      } catch (error) {
        console.log(error)
      }
    },

    // 删除申请
    async doDel(id) {
      try {
        const res = await delEmployee(id)
        this.$message.success(res.message)
        // 优化删除操作
        if (this.EmployeesList.length === 1) {
          this.page--
          if (this.page <= 0) {
            this.page = 1
          }
        }
        // 重发请求
        this.loadEmployeesList()
      } catch (err) {
        console.log(err)
      }
    },

    // 点击删除
    hDel(id) {
      this.$confirm('此操作将永久删除该员工, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 确定
        this.doDel(id)
      }).catch((err) => {
        console.log(err)
      })
    },

    // 子组件通知父组件
    hSuccess() {
      // 关闭弹层
      this.showDialog = false
      this.total++
      this.page = Math.ceil(this.total / this.size)
      // 刷新页面
      this.loadEmployeesList()
    },

    // 格式化时间
    dataFormat(time) {
      return dayjs(time).format('YYYY-MM-DD')
    },

    // 导出数据的格式化
    formatData(list) {
      const map = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      let header = []
      // header = ['id', 'mobile', 'username', .....]
      // data = [
      //     ['65c2', '1380000002', '管理员', ....],
      //     ['65c3', '1380000003', '孙财', ....],
      // ]
      let data = []
      // 开始代码
      // 找到一个元素
      const one = list[0]
      if (!one) {
        return { header, data }
      }
      header = Object.keys(one).map(key => {
        return map[key]
      })

      // data把list中每一个对象转成 对应的value数组
      data = list.map(obj => {
        // 把  Obj['formOfEmployment']: 1 , 2   ---> '正式'， '非正式'
        const key = obj['formOfEmployment'] // 1, 2
        obj['formOfEmployment'] = hireType[key] || '未知' // hireTypEnmu:{1:'正式', '2':'非正式' }

        return Object.values(obj)
      })

      return { header, data }
    },

    // 导入excel
    async hExportExcel() {
      // 1. 发送请求,拿到真实数据
      try {
        const res = await getEmployeesList({ page: this.page, size: this.total })
        console.log(res, 'excel')
        const list = res.data.rows
        // 2.将拿到的数据进行格式化操作
        const { header, data } = this.formatData(list)
        console.log('header', header)
        console.log('data', data)
        import('@/vendor/Export2Excel').then(excel => {
        // excel表示导入的模块对象
          console.log(excel)
          excel.export_json_to_excel({
            header: header, // 表头 必填
            data: data, // 具体数据 必填
            filename: 'xxw-hr-excel-list', // 文件名称
            autoWidth: true, // 宽度是否自适应
            bookType: 'xlsx' // 生成的文件类型
          })
        })
      } catch (error) {
        console.log(error)
      }
    },

    // 点击分配角色
    hAssignRole(id) {
      console.log(id)
      this.showDialogRole = true
      this.curId = id
    },

    hRoleSuccess() {
      // 关闭弹层
      this.showDialogRole = false
      // 刷新页面
      this.loadEmployeesList()
    }
  }

}
</script>
